<template>
    <div class="custom-editor" ref="editorContainerRef">
        <!-- 工具栏 -->
        <div class="editor-toolbar" :class="{ 'toolbar-fixed': isToolbarFixed }" ref="editorToolbarRef">
            <div class="toolbar-group">
                <div class="format-select-wrapper">
                    <select 
                        class="format-select"
                        @change="changeFormat($event)"
                        :value="currentFormat"
                    >
                        <option value="p">正文</option>
                        <option value="h1">标题 1</option>
                        <option value="h2">标题 2</option>
                        <option value="h3">标题 3</option>
                        <option value="h4">标题 4</option>
                        <option value="h5">标题 5</option>
                        <option value="h6">标题 6</option>
                    </select>
                </div>
                <button 
                    v-for="format in textFormats" 
                    :key="format.command"
                    class="toolbar-btn"
                    :class="{ active: isFormatActive(format.command) }"
                    :title="format.title"
                    @click="execCommand(format.command)"
                >
                    <i :class="format.icon">{{format.icon}}</i>
                </button>
            </div>

            <div class="toolbar-divider"></div>

            <div class="toolbar-group">
                <button 
                    v-for="align in alignments" 
                    :key="align.command"
                    class="toolbar-btn"
                    :class="{ active: isFormatActive(align.command) }"
                    :title="align.title"
                    @click="execCommand(align.command)"
                >
                    <i :class="align.icon">{{align.icon}}</i>
                </button>
            </div>

            <div class="toolbar-divider"></div>

            <div class="toolbar-group">
                <button 
                    v-for="list in lists" 
                    :key="list.command"
                    class="toolbar-btn"
                    :class="{ active: isFormatActive(list.command) }"
                    :title="list.title"
                    @click="execCommand(list.command)"
                >
                    <i :class="list.icon">{{list.icon}}</i>
                </button>
            </div>

            <div class="toolbar-divider"></div>

            <div class="toolbar-group">
                <div class="color-picker">
                    <input 
                        type="color" 
                        @change="changeColor"
                        title="文字颜色"
                    >
                </div>
                <!-- 添加背景颜色选择器 -->
                <div class="color-picker">
                    <input 
                        type="color" 
                        @change="changeBackgroundColor"
                        title="背景颜色"
                    >
                    <span class="color-picker-icon">🎨</span>
                </div>
                <button 
                    class="toolbar-btn"
                    title="插入链接"
                    @click="insertLink"
                >
                    🔗
                </button>
                <button 
                    class="toolbar-btn"
                    title="插入图片"
                    @click="triggerImageUpload"
                >
                    📷
                </button>
                <input 
                    type="file" 
                    ref="imageInput"
                    accept="image/*"
                    style="display: none"
                    @change="handleImageUpload"
                >
                <button 
                    class="toolbar-btn"
                    title="插入视频"
                    @click="openVideoDialog"
                >
                    🎥
                </button>
            </div>

            <div class="toolbar-divider"></div>

            <div class="toolbar-group">
                <button 
                    class="toolbar-btn"
                    title="插入表格"
                    @click="openTableDialog"
                >
                    📊
                </button>
            </div>

            <div class="toolbar-divider"></div>
            
            <div class="toolbar-group">
                <button 
                    class="toolbar-btn"
                    :class="{ active: isFormatActive('formatBlock') }"
                    title="引用"
                    @click="insertBlockquote"
                >" </button>
            </div>
        </div>

        <!-- 当工具栏固定时，添加一个占位符div以保持布局 -->
        <div class="toolbar-placeholder" 
        v-if="isToolbarFixed" 
        :style="{ height: toolbarHeight + 'px' }"></div>

        <!-- 编辑区域 -->
        <div 
            class="editor-content"
            ref="editorRef"
            contenteditable="true"
            @input="handleInput"
            @paste="handlePaste"
            @keydown="handleKeydown"
            @mouseup="handleEditorEvents"
            @keyup="handleEditorEvents"
            :placeholder="placeholder"
        ></div>
    </div>
    <!-- 表格插入对话框 -->
    <div v-if="showTableDialog" class="table-dialog-overlay">
        <div class="table-dialog">
            <h3>插入表格</h3>
            <div class="dialog-form">
                <div class="form-group">
                    <label>行数:</label>
                    <input v-model.number="tableConfig.rows" type="number" min="1" value="3">
                </div>
                <div class="form-group">
                    <label>列数:</label>
                    <input v-model.number="tableConfig.cols" type="number" min="1" value="2">
                </div>
                <div class="form-group">
                    <label>宽度:</label>
                    <input v-model="tableConfig.width" type="text" placeholder="默认500">
                </div>
                <div class="form-group">
                    <label>高度:</label>
                    <input v-model="tableConfig.height" type="text" placeholder="可为空">
                </div>
                <div class="form-group">
                    <label>间距:</label>
                    <input v-model.number="tableConfig.spacing" type="number" min="0" value="1">
                </div>
                <div class="form-group">
                    <label>对齐方式:</label>
                    <select v-model="tableConfig.align">
                        <option value="">没有设置</option>
                        <option value="left">左对齐</option>
                        <option value="center">居中</option>
                        <option value="right">右对齐</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>标题:</label>
                    <input v-model="tableConfig.title" type="text" placeholder="可为空">
                </div>
                <div class="form-group">
                    <label>摘要:</label>
                    <input v-model="tableConfig.summary" type="text" placeholder="可为空">
                </div>
                <div class="form-group">
                    <label>标题单元格:</label>
                    <select v-model="tableConfig.headerType">
                        <option value="none">无</option>
                        <option value="firstRow">第一行</option>
                        <option value="firstCol">第一列</option>
                        <option value="firstRowCol">第一行第一列</option>
                    </select>
                </div>
            </div>
            <div class="dialog-footer">
                <button @click="insertTable" class="btn-primary">确定</button>
                <button @click="showTableDialog = false" class="btn-secondary">取消</button>
            </div>
        </div>
    </div>
    <!-- 代码插入对话框 -->
    <div v-if="showCodeDialog" class="code-dialog-overlay">
        <div class="code-dialog">
            <h3>插入代码</h3>
            <div class="dialog-form">
                <div class="form-group">
                    <label>编程语言:</label>
                    <input 
                        v-model="codeConfig.language" 
                        type="text" 
                        placeholder="可选，如: javascript, python, java等"
                    >
                </div>
                <div class="form-group code-input">
                    <label>代码内容:</label>
                    <textarea 
                        v-model="codeConfig.code"
                        placeholder="在此输入代码..."
                        rows="10"
                    ></textarea>
                </div>
            </div>
            <div class="dialog-footer">
                <button @click="insertCode" class="btn-primary">确定</button>
                <button @click="showCodeDialog = false" class="btn-secondary">取消</button>
            </div>
        </div>
    </div>
    <!-- 视频插入对话框 -->
    <div v-if="showVideoDialog" class="video-dialog-overlay">
        <div class="video-dialog">
            <h3>插入视频</h3>
            <div class="dialog-form">
                <div class="form-group">
                    <label>视频来源：</label>
                    <select v-model="videoConfig.type">
                        <option value="url">在线视频</option>
                        <option value="upload">本地上传</option>
                    </select>
                </div>

                <!-- URL输入 -->
                <div v-if="videoConfig.type === 'url'" class="form-group">
                    <label>视频URL：</label>
                    <input 
                        v-model="videoConfig.url"
                        type="text"
                        placeholder="输入视频链接（支持YouTube、Bilibili等）"
                    >
                </div>

                <!-- 文件上传 -->
                <div v-else class="form-group">
                    <label>上传视频：</label>
                    <input 
                        type="file"
                        ref="videoFileInput"
                        accept="video/*"
                        @change="handleVideoFileChange"
                    >
                </div>

                <!-- 视频设置 -->
                <div class="form-group">
                    <label>宽度：</label>
                    <input 
                        v-model="videoConfig.width"
                        type="text"
                        placeholder="例如：100%或600px"
                    >
                </div>
                <div class="form-group">
                    <label>高度：</label>
                    <input 
                        v-model="videoConfig.height"
                        type="text"
                        placeholder="例如：400px"
                    >
                </div>
            </div>
            <div class="dialog-footer">
                <button @click="insertVideo" class="btn-primary">确定</button>
                <button @click="showVideoDialog = false" class="btn-secondary">取消</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, defineProps, defineEmits, onUnmounted} from 'vue'
import hljs from 'highlight.js';
import 'highlight.js/styles/vs2015.css'; // 可以选择其他主题样式
const props = defineProps<{
    modelValue: string;
    placeholder?: string;
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void;
    (e: 'change', value: string): void;
}>()

const editorRef = ref<HTMLElement>()
const imageInput = ref<HTMLInputElement>()

// 添加工具栏固定状态
const editorContainerRef = ref<HTMLElement | null>(null)
const editorToolbarRef = ref<HTMLElement | null>(null)
const isToolbarFixed = ref(false)
const toolbarHeight = ref(0)

// 处理滚动事件
// 添加节流函数来优化滚动性能
const throttle = <T extends (...args: any[]) => any>(fn: T, delay: number): ((...args: Parameters<T>) => void) => {
    let lastCall = 0;
    return (...args: Parameters<T>) => {
        const now = Date.now();
        if (now - lastCall >= delay) {
            fn(...args);
            lastCall = now;
        }
    };
};
// 使用节流的滚动处理
const handleScroll = () => {
    if (!editorContainerRef.value || !editorToolbarRef.value) return

    // 获取容器相对于视口的位置
    const containerRect = editorContainerRef.value.getBoundingClientRect()
    
    // 如果没有记录工具栏高度，则记录
    if (toolbarHeight.value === 0) {
        toolbarHeight.value = editorToolbarRef.value.offsetHeight
    }

    // 当容器顶部到达或超过视口顶部时，固定工具栏
    isToolbarFixed.value = containerRect.top <= 0
}
const throttledHandleScroll = throttle(handleScroll, 100);
// 文本格式化选项
const textFormats = [
    { command: 'bold', title: '粗体', icon: 'B' },
    { command: 'italic', title: '斜体', icon: 'I' },
    { command: 'underline', title: '下划线', icon: 'U' },
    { command: 'strikeThrough', title: '删除线', icon: 'S' }
]

// 对齐方式
const alignments = [
    { command: 'justifyLeft', title: '左对齐', icon: '←' },
    { command: 'justifyCenter', title: '居中对齐', icon: '↔' },
    { command: 'justifyRight', title: '右对齐', icon: '→' }
]

// 列表
const lists = [
    { command: 'insertUnorderedList', title: '无序列表', icon: '•' },
    { command: 'insertOrderedList', title: '有序列表', icon: '1.' }
]

// 当前格式
const currentFormat = ref('p')

// 更改文本格式
const changeFormat = (event: Event) => {
    const format = (event.target as HTMLSelectElement).value
    currentFormat.value = format
    execCommand('formatBlock', `<${format}>`)
}

// 更新当前格式（在选择位置变化时调用）
const updateCurrentFormat = () => {
    const formats = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
    for (const format of formats) {
        if (document.queryCommandValue('formatBlock').toLowerCase() === format) {
            currentFormat.value = format
            return
        }
    }
    currentFormat.value = 'p' // 默认为正文
}

// 监听选择位置变化
const handleSelectionChange = () => {
    updateCurrentFormat()
}

// 执行编辑命令
const execCommand = (command: string, value = '') => {
    document.execCommand(command, false, value)
    updateModelValue()
}

// 检查格式是否激活
const isFormatActive = (command: string) => {
    return document.queryCommandState(command)
}

// 更改文字颜色
const changeColor = (e: Event) => {
    const color = (e.target as HTMLInputElement).value;
    execCommand('foreColor', color);
    updateModelValue(); // 确保更新模型值
}

// 更改背景颜色
const changeBackgroundColor = (e: Event) => {
    const color = (e.target as HTMLInputElement).value;
    execCommand('backColor', color);
    updateModelValue();
}

// 插入链接
const insertLink = () => {
    const url = prompt('请输入链接地址:', 'http://')
    if (url) {
        execCommand('createLink', url)
    }
}

// 触发图片上传
const triggerImageUpload = () => {
    imageInput.value?.click()
}

// 处理图片上传
const handleImageUpload = async (e: Event) => {
    const files = (e.target as HTMLInputElement).files
    if (files && files[0]) {
        try {
            const formData = new FormData()
            formData.append('file', files[0])
            
            const response = await fetch('http://localhost:3000/api/upload/single', {
                method: 'POST',
                body: formData
            })
            
            if (!response.ok) {
                throw new Error('上传失败')
            }
            
            const result = await response.json()
            // 使用返回的URL插入图片
            execCommand('insertImage', `http://localhost:3000${result.file.url}`)
            
            // 清空input
            if (imageInput.value) {
                imageInput.value.value = ''
            }
        } catch (error) {
            console.error('Error uploading image:', error)
            alert('图片上传失败')
        }
    }
}

// 处理粘贴事件
const handlePaste = (e: ClipboardEvent) => {
    e.preventDefault()
    const text = e.clipboardData?.getData('text/plain')
    if (text) {
        document.execCommand('insertText', false, text)
    }
}

// 处理按键事件
const handleKeydown = (e: KeyboardEvent) => {
    if (e.key === 'Tab') {
        e.preventDefault()
        execCommand('insertHTML', '&nbsp;&nbsp;&nbsp;&nbsp;')
    }
}

// 处理输入事件
const handleInput = () => {
    if (editorRef.value) {
        const content = editorRef.value.innerHTML;
        emit('update:modelValue', content);
        emit('change', content);
    }
}

// 更新模型值
const updateModelValue = () => {
    if (editorRef.value) {
        const content = editorRef.value.innerHTML
        emit('update:modelValue', content)
        emit('change', content)
    }
}

// 表格配置
const showTableDialog = ref(false)
const tableConfig = ref({
    rows: 3,
    cols: 2,
    width: '500',
    height: '',
    spacing: 1,
    align: '',
    title: '',
    summary: '',
    headerType: 'none'
})

const openTableDialog = () => {
    showTableDialog.value = true
}

const insertTable = () => {
    const config = tableConfig.value
    // 添加 border-collapse 和 border 样式
    let style = `
        border-spacing: ${config.spacing}px;
        border-collapse: collapse;
        border: 1px solid #d9d9d9;
    `
    if (config.width) style += `width: ${config.width}px;`
    if (config.height) style += `height: ${config.height}px;`
    if (config.align) style += `text-align: ${config.align};`

    let tableHtml = `<table style="${style}">`

    // 添加标题
    if (config.title) {
        tableHtml += `<caption>${config.title}</caption>`
    }

    // 添加摘要
    if (config.summary) {
        tableHtml += `<caption style="display:none">${config.summary}</caption>`
    }

    // 生成表格内容，为单元格添加边框样式
    for (let i = 0; i < config.rows; i++) {
        tableHtml += '<tr>'
        for (let j = 0; j < config.cols; j++) {
            let isHeader = (
                config.headerType === 'firstRow' && i === 0 ||
                config.headerType === 'firstCol' && j === 0 ||
                config.headerType === 'firstRowCol' && i === 0 && j === 0
            )
            
            const cellStyle = 'style="border: 1px solid #d9d9d9; padding: 8px;"'
            
            if (isHeader) {
                tableHtml += `<th ${cellStyle} contenteditable="true">标题</th>`
            } else {
                tableHtml += `<td ${cellStyle} contenteditable="true">内容</td>`
            }
        }
        tableHtml += '</tr>'
    }
    
    tableHtml += '</table>'
    
    // 确保编辑器获得焦点
    if (editorRef.value) {
        // 保存当前的滚动位置
        const scrollTop = editorRef.value.scrollTop;

        // 在插入表格之前恢复选区
        restoreSelection();
        
        // 在当前光标位置插入表格 HTML
        execCommand('insertHTML', tableHtml);

        // 恢复滚动位置
        editorRef.value.scrollTop = scrollTop;
    }
    
    showTableDialog.value = false;
}
// 代码配置
const showCodeDialog = ref(false)
const lastRange = ref<Range | null>(null)
const codeConfig = ref({
    language: '',
    code: ''
})

// 添加新的插入引用方法
const insertBlockquote = () => {
    const selection = window.getSelection()
    if (!selection || !editorRef.value) return

    // 获取选中的内容
    const selectedText = selection.toString()
    
    // 准备引用块HTML
    let quoteHtml
    if (selectedText) {
        // 如果有选中文本，将其包含在引用块中
        quoteHtml = `<blockquote>${selectedText}</blockquote><p><br></p>`
    } else {
        // 如果没有选中文本，创建一个空的引用块
        quoteHtml = '<blockquote><p><br></p></blockquote><p><br></p>'
    }

    // 插入引用块
    execCommand('insertHTML', quoteHtml)
}
const saveSelection = () => {
    const selection = window.getSelection()
    if (selection && selection.rangeCount > 0) {
        lastRange.value = selection.getRangeAt(0).cloneRange()
    }
}
const restoreSelection = () => {
    if (lastRange.value && editorRef.value) {
        const selection = window.getSelection()
        selection?.removeAllRanges()
        selection?.addRange(lastRange.value)
    }
}
const handleEditorEvents = () => {
    saveSelection()
}
const insertCode = () => {
    const { language, code } = codeConfig.value
    if (!code.trim()) {
        alert('请输入代码内容')
        return
    }

    // 转义HTML特殊字符
    const escapedCode = code
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;')

    // 使用highlight.js进行代码高亮
    let highlightedCode = escapedCode;
    if (language) {
        try {
            highlightedCode = hljs.highlight(code, {
                language: language.toLowerCase(),
                ignoreIllegals: true
            }).value;
        } catch (e) {
            console.warn('Language not supported:', language);
            highlightedCode = escapedCode;
        }
    }

    const languageAttr = language ? ` class="language-${language}"` : ''
    // 修改代码块HTML，确保后面有一个可编辑的空行
    const codeHtml = `<pre style="position: relative;max-height: none;"><div class="code-header" style="position: absolute;top: 0;right: 0;padding: 4px 8px;font-size: 12px;color: #666;background: #f0f0f0;border-bottom-left-radius: 4px;">${language || 'plaintext'}</div><code${languageAttr}>${highlightedCode}</code></pre><p><br></p>`

    if (editorRef.value) {
        // 恢复之前保存的选区
        restoreSelection()
        
        // 确保编辑器获得焦点
        editorRef.value.focus()

        // 插入代码
        document.execCommand('insertHTML', false, codeHtml)

        // 将光标移动到新插入的空行
        const selection = window.getSelection()
        const range = document.createRange()
        const lastParagraph = editorRef.value.lastElementChild
        if (lastParagraph && lastParagraph.tagName.toLowerCase() === 'p') {
            range.setStart(lastParagraph, 0)
            range.collapse(true)
            selection?.removeAllRanges()
            selection?.addRange(range)
        }

        // 更新模型值
        updateModelValue()
    }
    
    showCodeDialog.value = false
}



// 添加常用编程语言列表
const commonLanguages = [
    'plaintext',
    'javascript',
    'typescript',
    'python',
    'java',
    'c',
    'cpp',
    'csharp',
    'php',
    'ruby',
    'swift',
    'go',
    'rust',
    'sql',
    'html',
    'css',
    'xml',
    'json',
    'yaml',
    'markdown',
    'bash',
    'shell',
]

// 视频配置
const showVideoDialog = ref(false)
const videoFileInput = ref<HTMLInputElement>()
const videoConfig = ref({
    type: 'url',
    url: '',
    file: null as File | null,
    width: '100%',
    height: '400px'
})

const openVideoDialog = () => {
    showVideoDialog.value = true
    videoConfig.value = {
        type: 'url',
        url: '',
        file: null,
        width: '100%',
        height: '400px'
    }
}

const handleVideoFileChange = (event: Event) => {
    const input = event.target as HTMLInputElement
    if (input.files && input.files[0]) {
        videoConfig.value.file = input.files[0]
    }
}

const insertVideo = async () => {
    let videoHtml = ''
    const { type, width, height } = videoConfig.value

    restoreSelection()

    if (type === 'url') {
        const url = videoConfig.value.url.trim()
        if (!url) {
            alert('请输入视频URL')
            return
        }

        // 处理不同平台的视频URL
        if (url.includes('youtube.com') || url.includes('youtu.be')) {
            // YouTube视频处理保持不变
            const videoId = extractYouTubeVideoId(url)
            if (videoId) {
                videoHtml = `
                    <div class="video-container" style="width: ${width};">
                        <div class="video-wrapper">
                            <iframe
                                src="https://www.youtube.com/embed/${videoId}"
                                frameborder="0"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                allowfullscreen
                            ></iframe>
                        </div>
                    </div>
                    <br/>
                `
            } else {
                alert('无效的YouTube视频链接')
                return
            }
        } else if (url.includes('bilibili.com') || url.includes('b23.tv')) {
            // Bilibili视频处理保持不变
            const videoId = extractBilibiliVideoId(url)
            if (videoId) {
                videoHtml = `
                    <div class="video-container" style="width: ${width};">
                        <div class="video-wrapper">
                            <iframe
                                src="//player.bilibili.com/player.html?bvid=${videoId}&page=1&high_quality=1&danmaku=0"
                                frameborder="0"
                                scrolling="no"
                                allowfullscreen
                            ></iframe>
                        </div>
                    </div>
                    <br/>
                `
            } else {
                alert('无效的Bilibili视频链接')
                return
            }
        } else {
            // 普通视频URL处理
            try {
                new URL(url) // 验证URL是否有效
                videoHtml = `
                    <div class="video-container" style="width: ${width};">
                        <div class="video-wrapper">
                            <video
                                controls
                                src="${url}"
                                controlsList="nodownload"
                                oncontextmenu="return false;"
                            >
                                您的浏览器不支持 video 标签
                            </video>
                        </div>
                    </div>
                    <br/>
                `
            } catch (e) {
                alert('请输入有效的视频URL')
                return
            }
        }
    } else {
        // 处理本地上传
        if (!videoConfig.value.file) {
            alert('请选择要上传的视频文件')
            return
        }

        try {
            const formData = new FormData()
            formData.append('file', videoConfig.value.file)
            
            const response = await fetch('http://localhost:3000/api/upload/single', {
                method: 'POST',
                body: formData
            })
            
            if (!response.ok) {
                throw new Error('上传失败')
            }
            
            const result = await response.json()
            const videoUrl = `http://localhost:3000${result.file.url}`
            
            videoHtml = `
                <div class="video-container" style="width: ${width};">
                    <div class="video-wrapper">
                        <video
                            controls
                            src="${videoUrl}"
                            controlsList="nodownload"
                            oncontextmenu="return false;"
                        >
                            您的浏览器不支持 video 标签
                        </video>
                    </div>
                </div>
                <br/>
            `
        } catch (error) {
            console.error('视频上传失败:', error)
            alert('视频上传失败')
            return
        }
    }

    if (videoHtml && editorRef.value) {
        editorRef.value.focus()
        setTimeout(() => {
            execCommand('insertHTML', videoHtml)
        }, 0)
    }

    showVideoDialog.value = false
}


// 辅助函数：提取YouTube视频ID
const extractYouTubeVideoId = (url: string) => {
    const regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/
    const match = url.match(regExp)
    return (match && match[7].length === 11) ? match[7] : null
}

// 辅助函数：提取Bilibili视频ID
const extractBilibiliVideoId = (url: string) => {
    // 支持多种B站URL格式
    const bvPattern = /(BV[a-zA-Z0-9]+)/i
    const avPattern = /(av\d+)/i
    
    let match = url.match(bvPattern)
    if (match) return match[1]
    
    match = url.match(avPattern)
    if (match) return match[1]
    
    return null
}

// 监听值变化
watch(() => props.modelValue, (newValue) => {
    if (editorRef.value && editorRef.value.innerHTML !== newValue) {
        // 只在编辑器没有焦点时更新内容
        if (document.activeElement !== editorRef.value) {
            editorRef.value.innerHTML = newValue;
        }
    }
})

// 初始化
onMounted(() => {
    document.addEventListener('selectionchange', handleSelectionChange)
    if (editorRef.value && props.modelValue) {
        editorRef.value.innerHTML = props.modelValue;
    }
    // 初始化工具栏高度
    if (editorToolbarRef.value) {
        toolbarHeight.value = editorToolbarRef.value.offsetHeight
    }
    
    // 添加滚动监听
    window.addEventListener('scroll', throttledHandleScroll)
})

// 在组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('scroll', throttledHandleScroll)
    document.removeEventListener('selectionchange', handleSelectionChange)
})
</script>
<style lang="less">
.custom-editor {
    .editor-content {
        min-height: 300px;
        padding: 16px;
        outline: none;
        overflow-y: auto;
        font-size: 14px;
        line-height: 1.6;
        color: #333;
        background: #fff;
        position: relative;
        z-index: 1;

        blockquote {
            margin: 1em 0;
            padding: 1em 2em;
            border-left: 4px solid var(--primary-color);
            background-color: #f8f9fa;
            color: #666;
            font-style: italic;
            position: relative;

            &:before {
                content: '"';
                font-size: 2em;
                color: var(--primary-color);
                line-height: 0.1em;
                margin-right: 0.25em;
                vertical-align: -0.4em;
                position: absolute; 
                left: 0.5em;
            }
            
            p {
                display: block;
                margin: 0;
                padding-left: 1em; // 添加这行，为引号留出空间
            }
        }
        
        &:empty:before {
            content: attr(placeholder);
            color: #999;
            position: absolute;  // 添加这行
            pointer-events: none;  // 添加这行
        }

        &:focus {
            outline: none;
        }

        img {
            max-width: 100%;
            height: auto;
        }

        a {
            color: var(--primary-color);
            text-decoration: none;

            &:hover {
                text-decoration: underline;
            }
        }
        p {
            margin: 0 0 1em;  // 添加段落间距
        }

        ul, ol {
            margin: 0 0 1em;
            padding-left: 2em;
        }
        .video-container {
            margin: 1em 0;
            max-width: 100%;
            
            .video-wrapper {
                position: relative;
                padding-bottom: 56.25%; /* 16:9 比例 */
                height: 0;
                overflow: hidden;
                
                iframe, video {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    border-radius: 4px;
                    background: #000;
                }
            }
        }
    }
}
</style>
<style lang="less" scoped>

.video-dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.video-dialog {
    background: white;
    padding: 20px;
    border-radius: 8px;
    min-width: 360px;
    max-width: 90%;

    h3 {
        margin: 0 0 20px 0;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
    }

    .dialog-form {
        .form-group {
            margin-bottom: 15px;

            label {
                display: block;
                margin-bottom: 8px;
                font-weight: 500;
            }

            input, select {
                width: 100%;
                padding: 8px 12px;
                border: 1px solid #ddd;
                border-radius: 4px;

                &:focus {
                    outline: none;
                    border-color: var(--primary-color);
                }
            }
        }
    }

    .dialog-footer {
        margin-top: 20px;
        text-align: right;
        gap: 10px;
        display: flex;
        justify-content: flex-end;

        button {
            padding: 6px 16px;
            border-radius: 4px;
            cursor: pointer;
            
            &.btn-primary {
                background: var(--primary-color);
                color: white;
                border: none;
            }
            
            &.btn-secondary {
                background: white;
                border: 1px solid #ddd;
            }
        }
    }
}
.code-dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.code-dialog {
    background: white;
    padding: 20px;
    border-radius: 8px;
    min-width: 600px;
    max-width: 90%;
    max-height: 90vh;
    overflow-y: auto;

    h3 {
        margin: 0 0 20px 0;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
    }

    .dialog-form {
        .form-group {
            margin-bottom: 15px;
            
            label {
                display: block;
                margin-bottom: 8px;
                font-weight: 500;
            }

            input, textarea {
                width: 100%;
                padding: 8px 12px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-family: 'Courier New', Courier, monospace;
                
                &:focus {
                    outline: none;
                    border-color: var(--primary-color);
                }
            }

            &.code-input textarea {
                min-height: 200px;
                resize: vertical;
            }
        }
    }

    .dialog-footer {
        margin-top: 20px;
        text-align: right;
        gap: 10px;
        display: flex;
        justify-content: flex-end;

        button {
            padding: 6px 16px;
            border-radius: 4px;
            cursor: pointer;
            
            &.btn-primary {
                background: var(--primary-color);
                color: white;
                border: none;
            }
            
            &.btn-secondary {
                background: white;
                border: 1px solid #ddd;
            }
        }
    }
}

.code-icon {
    font-style: normal;
    font-family: monospace;
    font-weight: bold;
}
.table-dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.table-dialog {
    background: white;
    padding: 20px;
    border-radius: 8px;
    min-width: 400px;
    max-width: 90%;
    max-height: 90vh;
    overflow-y: auto;

    h3 {
        margin: 0 0 20px 0;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
    }

    .dialog-form {
        .form-group {
            margin-bottom: 15px;
            display: flex;
            align-items: center;

            label {
                width: 100px;
                flex-shrink: 0;
            }

            input, select {
                flex: 1;
                padding: 6px 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                
                &:focus {
                    outline: none;
                    border-color: var(--primary-color);
                }
            }
        }
    }

    .dialog-footer {
        margin-top: 20px;
        text-align: right;
        gap: 10px;
        display: flex;
        justify-content: flex-end;

        button {
            padding: 6px 16px;
            border-radius: 4px;
            cursor: pointer;
            
            &.btn-primary {
                background: var(--primary-color);
                color: white;
                border: none;
            }
            
            &.btn-secondary {
                background: white;
                border: 1px solid #ddd;
            }
        }
    }
}
.custom-editor {
    border: 1px solid #ddd;
    border-radius: 4px;
    background: white;
    position: relative;
    .format-select-wrapper {
        position: relative;
        display: inline-block;
        
        &::after {
            content: '';
            position: absolute;
            top: 50%;
            right: 8px;
            transform: translateY(-50%);
            border-style: solid;
            border-width: 5px 5px 0 5px;
            border-color: #666 transparent transparent transparent;
            pointer-events: none;
        }
    }

    .format-select {
        width: 90px;
        height: 32px;
        padding: 0 24px 0 8px; // 右侧padding增加以容纳箭头
        border: 1px solid transparent;
        border-radius: 4px;
        outline: none;
        cursor: pointer;
        font-size: 14px;
        background-color: transparent;
        appearance: none;
        -webkit-appearance: none;
        -moz-appearance: none;
        color: #333;
        transition: all 0.2s;

        &:hover {
            background: #fff;
            border-color: #ddd;
        }

        &:focus {
            background: #fff;
            border-color: var(--primary-color);
        }

        option {
            background: white;
            color: #333;
            padding: 8px;
        }
    }
    .editor-toolbar {
        display: flex;
        padding: 8px;
        border-bottom: 1px solid #eee;
        background: #f8f9fa;
        gap: 4px;
        flex-wrap: wrap;
        z-index: 1000;
        width: 100%;
        box-sizing: border-box;
        &.toolbar-fixed {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            animation: slideDown 0.3s ease;
        }
        .toolbar-group {
            display: flex;
            gap: 4px;
        }

        .toolbar-divider {
            width: 1px;
            background: #ddd;
            margin: 0 8px;
        }

        .toolbar-btn {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid transparent;
            border-radius: 4px;
            background: transparent;
            cursor: pointer;
            transition: all 0.2s;
            color: #333;  // 修改文字颜色
            font-weight: bold;  // 添加粗体
            font-size: 14px;  // 调整字体大小

            &:hover {
                background: #fff;
                border-color: #ddd;
            }

            &.active {
                background: #e6f0ff;
                color: var(--primary-color);
                border-color: var(--primary-color);
            }

            i {
                font-style: normal;  // 确保图标文字正常显示
                line-height: 1;
                font-family: Arial, sans-serif;  // 使用基础字体
            }
        }

        .color-picker {
            position: relative;
            width: 32px;
            height: 32px;

            input[type="color"] {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                border: none;
                border-radius: 4px;
                padding: 0;
                cursor: pointer;

                &::-webkit-color-swatch-wrapper {
                    padding: 0;
                }

                &::-webkit-color-swatch {
                    border: none;
                    border-radius: 4px;
                }
            }
        }
    }
}
.toolbar-placeholder {
    transition: height 0.3s ease;
}
// 工具栏滑入动画
@keyframes slideDown {
    from {
        transform: translateY(-100%);
    }
    to {
        transform: translateY(0);
    }
}
// 确保固定工具栏的宽度与编辑器容器相同
@media screen and (min-width: 768px) {
    .editor-toolbar.toolbar-fixed {
        max-width: 1200px;
        margin: 0 auto;
    }
}

// 移动端适配
@media screen and (max-width: 767px) {
    .custom-editor {
        .editor-toolbar {
            &.toolbar-fixed {
                padding: 4px;
            }
        }
    }
}
</style>